package cn.sc.summer.auth.handler;

import cn.sc.summer.constant.util.SpringUtilX;
import cn.sc.summer.auth.token.store.DefaultTokenStore;
import cn.sc.summer.auth.token.store.base.BaseTokenStore;
import cn.sc.summer.token.base.BaseLoginToken;
import cn.sc.summer.token.po.UserDetailX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类名：登录成功拦截器
 *
 * @author a-xin
 * @date 2023/11/23 14:06
 */
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        if (authentication instanceof BaseLoginToken) {
            BaseLoginToken baseLoginToken = (BaseLoginToken) authentication;
            UserDetailX userDetailX = baseLoginToken.getUserInfo();
            try {
                BaseTokenStore baseTokenStore = SpringUtilX.getSupportBean(BaseTokenStore.class, baseLoginToken.getSupports(), DefaultTokenStore.class.newInstance());
                baseTokenStore.creatToken(request, response, authentication, userDetailX);
            } catch (Exception e) {
                throw new AuthenticationServiceException(e.getMessage());
            }
        } else {
            throw new AuthenticationServiceException("The account or password is incorrect！");
        }
    }

}
